// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { result} = require("xzs-utils")

module.exports = {
	_before: function () { // 通用预处理器
		
		this.startTime = Date.now()
		
		let body = this.getHttpInfo().body
		if (!body) {
			throw result(400, "required")
		}
		this.params = JSON.parse(body)
		
		this.dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		this.dbJQL.setUser({
			uid: '6614cee821821b6d2bf33d83',
			role: ['admin']
		})

	},
	
	async getList() {
		let {num=5, size=0, hot=false} = this.params
		let wer = "article_status == 1"
		if (hot) {
			wer = "article_status == 1 && is_essence == true"
		}
		let field = "avatar.url as picpath, title, author, publish_date, view_count"
		
		let res = await this.dbJQL.collection("xzs_news")
		.where(wer)
		.field(field)
		.orderBy("publish_date", "desc")
		.skip(size)
		.limit(num)
		.get()
		
		let count = await this.dbJQL.collection("xzs_news").where(wer).count()
		return result(0, "success", res.data, count.total)
	},
	
	async detail() {
		let {_id} = this.params
		if (!_id) return result(400, "required")
		let field = "title, author, publish_date, view_count, content"
		let res = await this.dbJQL.collection("xzs_news").doc(_id).field(field).get({
			getOne: true
		})
		return result(0, "success", res.data)
	},
	
	_after: async function(error, result) {
		if (error) {
			throw error
		}
		let timeCost = Date.now() - this.startTime
		result.timeCost = timeCost
		return result
	}
}
